from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from .models import Merchant, MenuItem
from orders.models import Order
from django.db.models import Avg
from datetime import datetime
from django.views.generic import ListView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Restaurant, MenuItem, Category


def merchant_list(request):
    """商家列表视图"""
    merchants = Merchant.objects.all().annotate(
        avg_rating=Avg('order__rating')
    ).order_by('-avg_rating')
    return render(request, 'merchant_list.html', {'merchants': merchants})


def merchant_detail(request, merchant_id):
    """商家详情视图"""
    merchant = get_object_or_404(Merchant, id=merchant_id)
    menu_items = merchant.menuitem_set.filter(is_available=True)
    return render(request, 'merchant_detail.html', {
        'merchant': merchant,
        'menu_items': menu_items
    })


def menu(request, merchant_id):
    """商家菜单视图"""
    merchant = get_object_or_404(Merchant, id=merchant_id)
    categories = merchant.menuitem_set.values_list('category', flat=True).distinct()
    menu_items = {}
    for category in categories:
        menu_items[category] = merchant.menuitem_set.filter(
            category=category,
            is_available=True
        )
    return render(request, 'menu.html', {
        'merchant': merchant,
        'categories': categories,
        'menu_items': menu_items
    })


@login_required
def merchant_dashboard(request):
    """商家管理后台"""
    if not hasattr(request.user, 'merchant'):
        messages.error(request, '您不是商家用户')
        return redirect('home')

    merchant = request.user.merchant
    pending_orders = Order.objects.filter(
        merchant=merchant,
        status='pending'
    ).order_by('-created_at')

    today_orders = Order.objects.filter(
        merchant=merchant,
        created_at__date=datetime.now().date()
    )

    context = {
        'merchant': merchant,
        'pending_orders': pending_orders,
        'today_orders': today_orders,
        'total_orders': today_orders.count(),
        'total_amount': sum(order.total_amount for order in today_orders)
    }
    return render(request, 'merchant_dashboard.html', context)


@login_required
def pending_orders(request):
    """待处理订单列表"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})

    orders = Order.objects.filter(
        merchant=request.user.merchant,
        status='pending'
    ).order_by('-created_at')
    return render(request, 'pending_orders.html', {'orders': orders})


@login_required
def completed_orders(request):
    """已完成订单列表"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})

    orders = Order.objects.filter(
        merchant=request.user.merchant,
        status='completed'
    ).order_by('-completed_at')
    return render(request, 'completed_orders.html', {'orders': orders})


@login_required
def manage_menu(request):
    """菜单管理"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})

    menu_items = MenuItem.objects.filter(merchant=request.user.merchant)
    return render(request, 'manage_menu.html', {'menu_items': menu_items})


@login_required
def add_menu_item(request):
    """添加菜品"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})

    if request.method == 'POST':
        name = request.POST.get('name')
        price = request.POST.get('price')
        description = request.POST.get('description')
        category = request.POST.get('category')
        image = request.FILES.get('image')

        MenuItem.objects.create(
            merchant=request.user.merchant,
            name=name,
            price=price,
            description=description,
            category=category,
            image=image
        )
        messages.success(request, '菜品添加成功')
        return redirect('manage_menu')
    return render(request, 'add_menu_item.html')


@login_required
def edit_menu_item(request, item_id):
    """编辑菜品"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})

    item = get_object_or_404(MenuItem, id=item_id, merchant=request.user.merchant)

    if request.method == 'POST':
        item.name = request.POST.get('name', item.name)
        item.price = request.POST.get('price', item.price)
        item.description = request.POST.get('description', item.description)
        item.category = request.POST.get('category', item.category)
        if 'image' in request.FILES:
            item.image = request.FILES['image']
        item.save()
        messages.success(request, '菜品更新成功')
        return redirect('manage_menu')
    return render(request, 'edit_menu_item.html', {'item': item})


@login_required
def delete_menu_item(request, item_id):
    """删除菜品"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})

    item = get_object_or_404(MenuItem, id=item_id, merchant=request.user.merchant)
    item.delete()
    messages.success(request, '菜品已删除')
    return redirect('manage_menu')


@login_required
def toggle_item_availability(request, item_id):
    """切换菜品可用状态"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})

    item = get_object_or_404(MenuItem, id=item_id, merchant=request.user.merchant)
    item.is_available = not item.is_available
    item.save()
    return JsonResponse({
        'status': 'success',
        'is_available': item.is_available
    })


@login_required
def process_order(request, order_id):
    """处理订单"""
    if not hasattr(request.user, 'merchant'):
        return JsonResponse({'status': 'error', 'message': '无权限访问'})

    order = get_object_or_404(Order, id=order_id, merchant=request.user.merchant)
    action = request.POST.get('action')

    if action == 'accept':
        order.status = 'preparing'
        messages.success(request, '订单已接受')
    elif action == 'reject':
        order.status = 'rejected'
        messages.success(request, '订单已拒绝')
    elif action == 'complete':
        order.status = 'completed'
        order.completed_at = datetime.now()
        messages.success(request, '订单已完成')

    order.save()
    return redirect('merchant_dashboard')


class RestaurantListView(ListView):
    model = Restaurant
    template_name = 'restaurants/restaurant_list.html'
    context_object_name = 'restaurants'
    paginate_by = 9

    def get_queryset(self):
        queryset = Restaurant.objects.filter(is_active=True)
        category = self.request.GET.get('category')
        if category:
            queryset = queryset.filter(categories__name=category)
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context


class RestaurantDetailView(DetailView):
    model = Restaurant
    template_name = 'restaurants/restaurant_detail.html'
    context_object_name = 'restaurant'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['menu_items'] = MenuItem.objects.filter(
            restaurant=self.object,
            is_available=True
        ).select_related('category')
        return context
